<?php
declare (strict_types = 1);

namespace app\command\logic;

use app\common\models\Member\MemberProfitPoolLog;
use app\common\models\Member\MemberWithdraw;
use app\common\models\Order\Order;
use app\common\models\Order\OrderPay;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 统计-财务概览
 * php think cli stats_finance_overview --msg='{"days":30}'
 */
class CliStatsShopFinanceOverviewLogic extends BaseLogic implements CliInterface
{

    public function run(Output $output, array $msg): bool
    {
        $insertData = [];
        //$date       = $msg['date'] ?? '';
        $date       = isset($msg['date']) ? ($msg['date'] == 'today' ? date('Y-m-d') : $msg['date']) : null;
        if ( ! empty($date)) {
            $insertData[] = self::dataForHome($date);
        } else {
            $days = intval($msg['days'] ?? 1);
            for ($i = 1; $i <= $days; $i++) {
                $date = date('Y-m-d', strtotime("-$i days"));
                // echo $date . "\n";exit;
                $insertData[] = self::dataForHome($date);
            }
        }
        if ( ! empty($insertData)) {
            \think\facade\Db::table('stats_finance_overview')
                ->replace()
                ->insertAll($insertData);
        }
        return true;
    }


    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    private function dataForHome($date): array
    {
        $end = $date . ' 23:59:59';


        $where = [
            ['status','=',1],
            ['audit_at', 'between', [$date, $end]],
        ];

        $MemberWithdraw = MemberWithdraw::getInstance()->where($where)->sum('amount');

        $where = [
            ['status','=',6],
            ['refund_at', 'between', [$date, $end]],
        ];
        $field = 'SUM(if(order_type=1 or order_type=3,pay_amount+pay_price,0)) as offline,
            SUM(if(order_type=2,pay_amount+pay_price,0)) as online,SUM(if(order_type=4,pay_amount+pay_price,0)) as supply';
        $orderRefund = Order::getInstance()->field($field)->where($where)->find();

        $where = [
            ['status','=',1],
            ['deleted','=',0],
            ['create_at', 'between', [$date, $end]],
        ];
        $field = 'SUM(if(type=1,amount,0)) as online,
            SUM(if(type=2,amount,0)) as offline,SUM(if(type=3,amount,0)) as supply,
            SUM(if(type=4,amount,0)) as community,SUM(if(type=5,amount,0)) as packs';
        $profit = MemberProfitPoolLog::getInstance()->field($field)->where($where)->find();

        $where = [
            ['status','=',1],
            ['create_at','between', [$date, $end]]
        ];

        $orderPay = orderPay::getInstance()->field('DATE(create_at) as order_date, SUM(if(order_status=0 and status=1,pay_amount+pay_price,0)) as online,
        SUM(if(order_status=6 and status=1,pay_amount+pay_price,0)) as offline,SUM(if(order_status=1 and status=1,community_pay_amount+pay_price,0)) as community,
        SUM(if(order_status=3 and status=1,community_pay_amount+pay_price,0)) as packs,SUM(if(order_status=4 and status=1,pay_amount+pay_price,0)) as op,
        SUM(if(order_status=5 and status=1,pay_amount+pay_price,0)) as supply')
            ->where($where)
            ->find();

        $data = [
            'online' => $orderPay['online'],
            'offline' => $orderPay['offline'],
            'supply' => $orderPay['supply'],
            'community' => bcadd((string)$orderPay['community'], (string)$orderPay['op'], 2),
            'packs' => $orderPay['packs'],
            'member_withdraw' => $MemberWithdraw ?: 0,
            'shop_withdraw' => 0,
            'online_refund' => $orderRefund['online'] ?: 0,
            'offline_refund' => $orderRefund['offline'] ?: 0,
            'supply_refund' => $orderRefund['supply'] ?: 0,
            'online_profit' => $profit['online'] ?: 0,
            'offline_profit' => $profit['offline'] ?: 0,
            'supply_profit' => $profit['supply'] ?: 0,
            'community_profit' => $profit['community'] ?: 0,
            'packs_profit' => $profit['packs'] ?: 0,
            'create_at' => date('Y-m-d H:i:s'),
        ];

        $data['date'] = $date;

        return $data;
    }
}
